from flask import Blueprint, render_template, request, session

import hashlib

from utils.database_util import query_data
user_center = Blueprint('user_center', __name__)
@user_center.route('/login',methods=['GET','POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        password = hashlib.md5(password.encode()).hexdigest()
        sql = "select * from users where username='%s'and password='%s'" % (username,password)
        result = query_data(sql)
        if len(result) == 0:
            return render_template('login.html',info='用户名或密码错误')
        else:
            session['username'] = username
            session['islogin'] = 'true'
            session['userid'] = result[0].get('userid')
            session['nickname'] = result[0].get('nickname')
            session['role'] = result[0].get('role')
        return render_template('home.html')
    else:
        return render_template('login.html')
@user_center.route('/register',methods=['GET','POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        nickname = request.form.get('nickname')

        password = hashlib.md5(password.encode()).hexdigest()
        sql = "insert into users(username,password,nickname) values('%s','%s','%s')" % (username,password,nickname)
        print(sql)
        result = query_data(sql)
        login()
        return render_template('home.html')
    else:
        return render_template('register.html')

@user_center.route('/logout', methods=['GET'])
def logout():
    # 清除会话中的用户信息
    session.pop('username', None)
    session.pop('islogin', None)
    session.pop('userid', None)
    session.pop('nickname', None)
    session.pop('role', None)
    # 重定向到登录页面
    return render_template('home.html')

@user_center.route('/my_favorite')
def favorite():
    return render_template('my_favorite.html')
@user_center.route('/user_center')

def user():
    return render_template('user_center.html')